<?php

namespace App\Http\Rest\Demo;

use Framework\Foundation\Database\FDB;
use Framework\Foundation\Response\ResponseGen;

class DbResource
{
    public function getList(array $restParams, $request)
    {
        $page = $request->getIn('page', 1);
        $pageSize = $request->getIn('page_size', 10);

        $query = FDB::from($restParams['resource'])->where($restParams['field'], $restParams['id']);

        // 作一些其他参数where条件

        $total = $query->count();

        $query->offset($pageSize * ($page - 1))->limit($pageSize);
        $ret = $query->fetchAll();

        return ResponseGen::success(['total' => $total, 'rows' => $ret]);
    }

    public function getInfo(array $restParams)
    {
        $query = FDB::from($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $info = $query->fetch();
        return ResponseGen::success($info);
    }

    public function post(array $restParams, $request)
    {
        $params = $request->getParsedBody();

        // 参数验证

        $query = FDB::insertInto($restParams['resource']);
        $ret = $query->values($params)->execute();
        if (!$ret) {
            return ResponseGen::error(400, "添加失败");
        }
        return ResponseGen::success();
    }


    public function put(array $restParams, $request)
    {
        // 参数验证
        $params = $request->getParsedBody();

        $query = FDB::update($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $ret = $query->set($params)->execute();

        if (!$ret) {
            return ResponseGen::error(400, "列新失败");
        }
        return ResponseGen::success();
    }

    public function del(array $restParams)
    {
        $query = FDB::update($restParams['resource'])->where($restParams['field'], $restParams['id']);
        $ret = $query->set([
            'is_deleted' => 1,
            'deleted_at' => date('Y-m-d H:i:s')
        ])->execute();
        if (!$ret) {
            return ResponseGen::error(400, "删除失败");
        }
        return ResponseGen::success();
    }
}
